var Poker = require("poker");
var Toast = require("toast");

cc.Class({
    extends: cc.Component,

    properties: {
        gou_spriteframe: cc.SpriteFrame,
        cha_spriteframe: cc.SpriteFrame,
        
        _handCards: [],                         //手牌数组
        _gameNode: null,                        //传入game的节点
        
        handCards_dataArray: [],                //手牌数组，类型是poker()
        announcementArray: [],
        
        toudaospliceArray: [],                  //加入头道的牌数组
        zhongdaospliceArray: [],                //加入中道的牌数组
        weidaospliceArray: [],                  //加入尾道的牌数组
        
        isReady_toudao: false,                  //判断头道是否完成牌阵
        isReady_zhongdao: false,                //判断中道是否完成牌阵
        isReady_weidao: false,                  //判断尾道是否完成牌阵
        
        handCards: {
            get: function () {
                return this._handCards;
            },
            set: function (value) {
                this._handCards = value;
            },
        },
        
        gameNode: {
            get: function () {
                return this._gameNode;
            },
            set: function (value) {
                this._gameNode = value;
            },
        },
    },

    onLoad: function () {
        this.initHandCards();
        this.setInputControl();
        this.initData();
        //屏蔽底部点击事件
        cc.find('mask', this.node).on(cc.Node.EventType.TOUCH_START, function (event) {});
    },
    
    //初始化数据
    initData: function () {
        this.isReady_toudao = false;
        this.isReady_zhongdao = false;
        this.isReady_weidao = false;
        this.announcementArray = [0, 0, 0, 0, 0, 0, 0, 0];
        
        var self = this;
        //给卡牌组合按钮添加点击事件
        for (let i = 0; i < 8; i++) {
            var btn_node = cc.find("choosecard_bg/node_btn/btn_0" + i, this.node);
            btn_node.on(cc.Node.EventType.TOUCH_END, function (event) {
                self.onAutoChooseCards(i);
            });
        }
        
        //给头道中道尾道右侧按钮添加事件
        for (let i = 0; i < 3; i++) {
            var btn_dao_node = cc.find("choosecard_bg/node_bikuang/btn_dao" + i, this.node);
            btn_dao_node.on(cc.Node.EventType.TOUCH_END, function (event) {
                self.onCancelBtn(i);
            });
        }
    },
    
    //创建手牌
    initHandCards: function () {
        var self = this;
        for (let i = 0; i < this._handCards.length; i++) {
            var card = new Poker(this._handCards[this._handCards.length - i - 1]);
            var card_node = this.onCreateSprite("poker_" + card.getId());
            card_node.tag = this._handCards[this._handCards.length - i -1];
            card_node.setPosition(cc.p((-parseInt(this._handCards.length / 2) + i) * 75, -170));
            this.node.addChild(card_node, 100 + i);
            this.handCards_dataArray.push(card);
            card.setNode(card_node);
        }
        this.checkAnnouncement();
    },
    
    //检查卡牌存在什么组合
    checkAnnouncement: function () {
        var count = 0;
        var duizi = 0;
        var hulu_san = 0;
        var hulu_dui = 0;
        var typeArray = [[],[],[],[]];
        var rankArray = [[],[],[],[],[],[],[],[],[],[],[],[],[]];
        for (let i = 0; i < this.handCards_dataArray.length; i++) {
            switch (this.handCards_dataArray[i].getType()) {
                case 0:typeArray[0].push(i);break;
                case 1:typeArray[1].push(i);break;
                case 2:typeArray[2].push(i);break;
                case 3:typeArray[3].push(i);break;
            }
            switch (this.handCards_dataArray[i].getRank()) {
                case 2:rankArray[0].push(i);break;
                case 3:rankArray[1].push(i);break;
                case 4:rankArray[2].push(i);break;
                case 5:rankArray[3].push(i);break;
                case 6:rankArray[4].push(i);break;
                case 7:rankArray[5].push(i);break;
                case 8:rankArray[6].push(i);break;
                case 9:rankArray[7].push(i);break;
                case 10:rankArray[8].push(i);break;
                case 11:rankArray[9].push(i);break;
                case 12:rankArray[10].push(i);break;
                case 13:rankArray[11].push(i);break;
                case 14:rankArray[12].push(i);break;
            }
        }
        
        //判断同花或者同花顺
        for (let i = 0; i < typeArray.length; i++) {
            var temp = 0;
            var arr = [];
            if (typeArray[i].length > 4) {
                if (i === 0) {
                    cc.log("方块存在同花");
                } else if (i === 1) {
                    cc.log("梅花存在同花");
                } else if (i === 2) {
                    cc.log("红心存在同花");
                } else if (i === 3) {
                    cc.log("黑桃存在同花");
                }
                this.announcementArray[4] = 1;
                for (let j = 0; j < typeArray[i].length; j++) {
                    if (rankArray[i].length) {
                        count++;
                        if (count >= 5) {
                            this.announcementArray[7] = 1;
                            cc.log("存在同花顺" + arr[0] + "," + arr[1] + "," + arr[2] + "," + arr[3] + "," + arr[4]);
                        }
                    } else {
                        count = 0;
                    }
            
                    if (temp - this.handCards_dataArray[typeArray[i][j]].getRank() === 1) {
                        temp = this.handCards_dataArray[typeArray[i][j]].getRank();
                        arr.push(temp);
                        count++;
                        if (count === 4) {
                            this.announcementArray[7] = 1;
                            cc.log("存在同花顺" + arr[0] + "," + arr[1] + "," + arr[2] + "," + arr[3] + "," + arr[4]);
                        }
                    } else {
                        if (temp === this.handCards_dataArray[typeArray[i][j]].getRank()) {
                            temp = this.handCards_dataArray[typeArray[i][j]].getRank();
                        } else {
                            arr.length = 0;
                            temp = this.handCards_dataArray[typeArray[i][j]].getRank();
                            arr.push(temp);
                            count = 0;
                        }
                    }
                }
            }
        }
        //判断顺子
        count = 0;
        for (let i = 0; i < rankArray.length; i++) {
            if (rankArray[i].length) {
                count++;
                if (count >= 5) {
                    this.announcementArray[3] = 1;
                    cc.log("存在同花顺" + arr[0] + "," + arr[1] + "," + arr[2] + "," + arr[3] + "," + arr[4]);
                }
            } else {
                count = 0;
            }
        }
        
        for (let i = 0; i < rankArray.length; i++) {
            if (rankArray[i].length > 3) {
                this.announcementArray[6] = 1;
                cc.log("存在铁支" + (i + 2));
                if (!hulu_san) {
                    hulu_san++;
                } else {
                    hulu_dui++;
                }
                duizi++;
            } else if (rankArray[i].length > 2) {
                this.announcementArray[2] = 1;
                cc.log("存在三条" + (i + 2));
                if (!hulu_san) {
                    hulu_san++;
                } else {
                    hulu_dui++;
                }
                duizi++;
            } else if (rankArray[i].length > 1) {
                this.announcementArray[0] = 1;
                cc.log("存在一对" + (i + 2));
                hulu_dui++;
                duizi++;
            } else {
                //没有对的
            }
            if (duizi >= 2) {
                this.announcementArray[1] = 1;
                cc.log("存在两对" + (i + 2));
            }
            if (hulu_san && hulu_dui) {
                this.announcementArray[5] = 1;
                cc.log("存在葫芦");
            }
        }
        
        for (let i = 0; i < this.announcementArray.length; i++) {
            var btn_node = cc.find("choosecard_bg/node_btn/btn_0" + i, this.node);
            btn_node.active = true;
            if (!this.announcementArray[i]) {
                btn_node.active = false;
            }
        }
        this.announcementArray = [0, 0, 0, 0, 0, 0, 0, 0];
    },
    
    //点击完成的按钮
    onWancheng: function () {
        if (this.isReady_toudao && this.isReady_zhongdao && this.isReady_weidao) {
            cc.log("完成选牌，开始比牌");
            var toudaoArray = [];
            var zhongdaoArray = [];
            var weidaoArray = [];
            this._gameNode.onFinishChooseCard(this.toudaospliceArray, this.zhongdaospliceArray, this.weidaospliceArray);
        } else {
            Toast.show("没有选完所有牌，请选完牌再重试", this.node);
        }
    },
    
    //创建精灵
    onCreateSprite: function (spriteframe) {
        var node = new cc.Node();
        var sprite = node.addComponent(cc.Sprite);
        if (spriteframe) {
            sprite.spriteFrame = cc.spriteFrameCache.getSpriteFrame(spriteframe);
        }
        return node;
    },
    
    //刷新手牌
    updataHandCards: function () {
        this.handCards_dataArray.sort(function (a, b) {
            return parseInt(b.getPid()) - parseInt(a.getPid());
        });
        for (let i = 0; i < this.handCards_dataArray.length; i++) {
            this.handCards_dataArray[i].setTouched(false);
            this.handCards_dataArray[i].getNode().setPosition(cc.p((-parseInt(this.handCards_dataArray.length / 2) + i) * 75, -170));
        }
        this.checkAnnouncement();
    },
    
    //添加点击事件
    setInputControl: function () {
        var self = this;
        var bg_node = cc.find("choosecard_bg", this.node);
        cc.eventManager.addListener({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            onTouchBegan: function (touches, event) {
                return true;
            },
            onTouchMoved: function (touches, event) {
            },
            onTouchEnded: function (touches, event) {
                var temp = touches.getLocation();
                for (var i = self.handCards_dataArray.length - 1; i >= 0; i--) {
                    var position = self.handCards_dataArray[i].getNode().getPosition();
                    if (Math.abs(temp.x - (position.x + 640)) < self.handCards_dataArray[i].getNode().width * 0.5 &&
                        Math.abs(temp.y - (position.y + 360)) < self.handCards_dataArray[i].getNode().height * 0.5) {
                        cc.log("touch index " + i);
                        if (!self.handCards_dataArray[i].getTouched()) {
                            self.handCards_dataArray[i].setTouched(true);
                            self.handCards_dataArray[i].getNode().setPositionY(self.handCards_dataArray[i].getNode().y + 20);
                        } else {
                            self.handCards_dataArray[i].setTouched(false);
                            self.handCards_dataArray[i].getNode().setPositionY(self.handCards_dataArray[i].getNode().y - 20);
                        }
                        return;
                    }
                }
            },
            onTouchCancelled: function (touches, event) {
            },
        }, bg_node);
    },
    
    //自动选择牌型
    onAutoChooseCards: function (index) {
        var count = 0;
        var temp = 0;
        var num = [[],[],[],[]];
        var arr = [];
        this.onRefreshAllCard();
        switch (index) {
            case 0://对子
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    if (i === this.handCards_dataArray.length - 1) {
                        cc.error("不存在对子");
                        return;
                    }
                    if (this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 1].getRank()) {
                        this.onMoveUpThisNode(i);
                        this.onMoveUpThisNode(i + 1);
                        return;
                    }
                }
                break;
            case 1://两对
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    for (let j = i + 1; j < this.handCards_dataArray.length - 1; j++) {
                        if (this.handCards_dataArray[i].getRank() === this.handCards_dataArray[j].getRank() &&
                        this.handCards_dataArray[i].getRank() != temp) {
                            this.onMoveUpThisNode(i);
                            this.onMoveUpThisNode(j);
                            temp = this.handCards_dataArray[i].getRank();
                            i++;
                            j++;
                            count++;
                            if (count == 2) {
                                return;
                            }
                        }
                    }
                }
                cc.error("不存在两对");
                break;
            case 2://三条
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    if (i === this.handCards_dataArray.length - 2) {
                        cc.error("不存在三对");
                        return;
                    }
                    if (this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 1].getRank() && 
                    this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 2].getRank()) {
                        this.onMoveUpThisNode(i);
                        this.onMoveUpThisNode(i + 1);
                        this.onMoveUpThisNode(i + 2);
                        return;
                    }
                }
                break;
            case 3://顺子
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    if (temp - this.handCards_dataArray[i].getRank() === 1) {
                        temp = this.handCards_dataArray[i].getRank();
                        arr.push(i);
                        count++;
                        if (count === 4) {
                            for (let j = 0; j < arr.length; j++) {
                                this.onMoveUpThisNode(arr[j]);
                            }
                            return;
                        }
                    } else {
                        if (temp === this.handCards_dataArray[i].getRank()) {
                            temp = this.handCards_dataArray[i].getRank();
                        } else {
                            arr.length = 0;
                            temp = this.handCards_dataArray[i].getRank();
                            arr.push(i);
                            count = 0;
                        }
                    }
                }
                cc.error("不存在顺子");
                break;
            case 4://同花
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    switch (this.handCards_dataArray[i].getType()) {
                        case 0:
                            num[0].push(i);
                            break;
                        case 1:
                            num[1].push(i);
                            break;
                        case 2:
                            num[2].push(i);
                            break;
                        case 3:
                            num[3].push(i);
                            break;
                    }
                }
                for (let i = 0; i < num.length; i++) {
                    if (num[i].length >= 5) {
                        for (let j = 0; j < num[i].length; j++) {
                            this.onMoveUpThisNode(num[i][j]);
                            if (j === 4) {
                                return;
                            }
                        }
                    }
                }
                cc.error("不存在同花");
                break;
            case 5://葫芦
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    if (i === this.handCards_dataArray.length - 2) {
                        cc.error("不存在葫芦");
                        return;
                    }
                    if (this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 1].getRank() && 
                    this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 2].getRank()) {
                        arr.push(i);
                        arr.push(i + 1);
                        arr.push(i + 2);
                        break;
                    }
                }
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    if (i === this.handCards_dataArray.length - 1) {
                        cc.error("不存在葫芦");
                        return;
                    }
                    temp = 0;
                    if (this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 1].getRank()) {
                        for (let j = 0; j < arr.length; j++) {
                            if (i === arr[j]) {
                                temp = 1;
                            }
                        }
                        if (!temp) {
                            arr.push(i);
                            arr.push(i + 1);
                            break;
                        }
                    }
                }
                for (let i = 0; i < arr.length; i++) {
                    this.onMoveUpThisNode(arr[i]);
                }
                break;
            case 6://铁支
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    if (i === this.handCards_dataArray.length - 3) {
                        cc.error("不存在铁支");
                        return;
                    }
                    if (this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 1].getRank() && 
                    this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 2].getRank() &&
                    this.handCards_dataArray[i].getRank() === this.handCards_dataArray[i + 3].getRank()) {
                        this.onMoveUpThisNode(i);
                        this.onMoveUpThisNode(i + 1);
                        this.onMoveUpThisNode(i + 2);
                        this.onMoveUpThisNode(i + 3);
                        return;
                    }
                }
                break;
            case 7://同花顺
                for (let i = 0; i < this.handCards_dataArray.length; i++) {
                    switch (this.handCards_dataArray[i].getType()) {
                        case 0:
                            num[0].push(i);
                            break;
                        case 1:
                            num[1].push(i);
                            break;
                        case 2:
                            num[2].push(i);
                            break;
                        case 0:
                            num[3].push(i);
                            break;
                    }
                }
                for (let i = 0; i < num.length; i++) {
                    if (num[i].length >= 5) {
                        for (let j = 0; j < num[i].length; j++) {
                            if (temp - this.handCards_dataArray[num[i][j]].getRank() === 1) {
                                temp = this.handCards_dataArray[num[i][j]].getRank();
                                arr.push(num[i][j]);
                                count++;
                                if (count === 4) {
                                    for (let k = 0; k < arr.length; k++) {
                                        this.onMoveUpThisNode(arr[k]);
                                    }
                                    return;
                                }
                            } else {
                                if (temp === this.handCards_dataArray[num[i][j]].getRank()) {
                                    temp = this.handCards_dataArray[num[i][j]].getRank();
                                } else {
                                    arr.length = 0;
                                    temp = this.handCards_dataArray[num[i][j]].getRank();
                                    arr.push(num[i][j]);
                                    count = 0;
                                }
                            }
                        }
                    }
                }
                cc.error("不存在同花顺");
                break;
            default:
                break;
        }
    },
    
    //判断当前节点是否可以升起
    onMoveUpThisNode: function (index) {
        if (!this.handCards_dataArray[index].getTouched()) {
            this.handCards_dataArray[index].setTouched(true);
            this.handCards_dataArray[index].getNode().setPositionY(this.handCards_dataArray[index].getNode().y + 20);
        }
    },
    
    //重置全部牌位置
    onRefreshAllCard: function () {
        for (let i = 0; i < this.handCards_dataArray.length; i++) {
            if (this.handCards_dataArray[i].getTouched()) {
                this.handCards_dataArray[i].setTouched(false);
                this.handCards_dataArray[i].getNode().setPositionY(this.handCards_dataArray[i].getNode().y - 20);
            }
        }
    },
    
    //点击头道
    onTouchToudao: function () {
        var count = 0;
        for (let i = 0; i < this.handCards_dataArray.length; i++) {
            if (this.handCards_dataArray[i].getTouched()) {
                count++;
            }
        }
        if (count > 3) {
            Toast.show("选牌数量超过三张", this.node);
        } else if (count < 3) {
            Toast.show("选牌数量没达到要求的三张", this.node);
        } else {
            //满足条件
            var toudao_node = cc.find("choosecard_bg/node_bikuang/node_toudao", this.node);
            this.onEnterDao(0, toudao_node);
        }
    },
    
    //点击中道
    onZhongdao: function () {
        var count = 0;
        for (let i = 0; i < this.handCards_dataArray.length; i++) {
            if (this.handCards_dataArray[i].getTouched()) {
                count++;
            }
        }
        if (count > 5) {
            Toast.show("选牌数量超过五张", this.node);
        } else if (count < 5) {
            Toast.show("选牌数量没达到要求的五张", this.node);
        } else {
            //满足条件
            var zhongdao_node = cc.find("choosecard_bg/node_bikuang/node_zhongdao", this.node);
            this.onEnterDao(1, zhongdao_node);
        }
    },
    
    //点击尾道
    onWeidao: function () {
        var count = 0;
        for (let i = 0; i < this.handCards_dataArray.length; i++) {
            if (this.handCards_dataArray[i].getTouched()) {
                count++;
            }
        }
        if (count > 5) {
            Toast.show("选牌数量超过五张", this.node);
        } else if (count < 5) {
            Toast.show("选牌数量没达到要求的五张", this.node);
        } else {
            //满足条件
            var weidao_node = cc.find("choosecard_bg/node_bikuang/node_weidao", this.node);
            this.onEnterDao(2, weidao_node);
        }
    },
    
    //点击头中尾道后的回调
    onEnterDao: function (type, Pnode) {
        var arr = [];
        var brr = [];
        var count = 0;
        for (let i = 0; i < this.handCards_dataArray.length; i++) {
            if (this.handCards_dataArray[i].getTouched()) {
                arr.push(this.handCards_dataArray[i].getNode());
                if (type === 0) {
                    this.toudaospliceArray.push(this.handCards_dataArray[i]);
                } else if (type === 1) {
                    this.zhongdaospliceArray.push(this.handCards_dataArray[i]);
                } else {
                    this.weidaospliceArray.push(this.handCards_dataArray[i]);
                }
                this.handCards_dataArray[i].setTouched(false);
                brr.push(i);
            }
        }
        for (let i = 0; i < brr.length; i++) {
            this.handCards_dataArray.splice(brr[i] - count, 1);
            count++;
        }
        for (let i = 0; i < arr.length; i++) {
            if (type === 0) {
                this.onShowSpriteFrame(0, true);
                arr[i].setPosition(cc.p((-parseInt(arr.length / 2) + i) * 75, 0));
            } else if (type === 1) {
                this.onShowSpriteFrame(1, true);
                arr[i].setPosition(cc.p((-parseInt(arr.length / 2) + i) * 62, 0));
            } else {
                this.onShowSpriteFrame(2, true);
                arr[i].setPosition(cc.p((-parseInt(arr.length / 2) + i) * 75, 0));
            }
            arr[i].parent = Pnode;
        }
        this.updataHandCards();
    },
    
    //变更精灵帧和属性
    onShowSpriteFrame: function (type, isbool) {
        if (type == 0) {
            this.isReady_toudao = isbool;
        } else if (type == 1) {
            this.isReady_zhongdao = isbool;
        } else {
            this.isReady_weidao = isbool;
        }
        var btn_node = cc.find("choosecard_bg/node_bikuang/btn_dao" + type, this.node);
        if (isbool) {
            btn_node.getComponent(cc.Sprite).spriteFrame = this.cha_spriteframe;
            if (type == 0) {
                var toudao_node = cc.find("choosecard_bg/node_bikuang/node_toudao", this.node);
                toudao_node.getComponent(cc.Button).interactable = false;
            } else if (type == 1) {
                var zhongdao_node = cc.find("choosecard_bg/node_bikuang/node_zhongdao", this.node);
                zhongdao_node.getComponent(cc.Button).interactable = false;
            } else {
                var weidao_node = cc.find("choosecard_bg/node_bikuang/node_weidao", this.node);
                weidao_node.getComponent(cc.Button).interactable = false;
            }
        } else {
            btn_node.getComponent(cc.Sprite).spriteFrame = this.gou_spriteframe;
            if (type == 0) {
                var toudao_node = cc.find("choosecard_bg/node_bikuang/node_toudao", this.node);
                toudao_node.getComponent(cc.Button).interactable = true;
            } else if (type == 1) {
                var zhongdao_node = cc.find("choosecard_bg/node_bikuang/node_zhongdao", this.node);
                zhongdao_node.getComponent(cc.Button).interactable = true;
            } else {
                var weidao_node = cc.find("choosecard_bg/node_bikuang/node_weidao", this.node);
                weidao_node.getComponent(cc.Button).interactable = true;
            }
        }
    },
    
    //点击取消或确定按钮回调
    onCancelBtn: function (index) {
        var temp = [];
        var dao_node;
        if (index == 0) {
            if (!this.isReady_toudao) {
                this.onTouchToudao();
                return;
            }
            dao_node = cc.find("choosecard_bg/node_bikuang/node_toudao", this.node);
            this.onShowSpriteFrame(0, false);
            for (let i = 0; i < this.toudaospliceArray.length; i++) {
                this.handCards_dataArray.push(this.toudaospliceArray[i]);
            }
            this.toudaospliceArray.length = 0;
        } else if (index == 1) {
            if (!this.isReady_zhongdao) {
                this.onZhongdao();
                return;
            }
            dao_node = cc.find("choosecard_bg/node_bikuang/node_zhongdao", this.node);
            this.onShowSpriteFrame(1, false);
            for (let i = 0; i < this.zhongdaospliceArray.length; i++) {
                this.handCards_dataArray.push(this.zhongdaospliceArray[i]);
            }
            this.zhongdaospliceArray.length = 0;
        } else {
            if (!this.isReady_weidao) {
                this.onWeidao();
                return;
            }
            dao_node = cc.find("choosecard_bg/node_bikuang/node_weidao", this.node);
            this.onShowSpriteFrame(2, false);
            for (let i = 0; i < this.weidaospliceArray.length; i++) {
                this.handCards_dataArray.push(this.weidaospliceArray[i]);
            }
            this.weidaospliceArray.length = 0;
        }
        
        for (let i = 0; i < dao_node.children.length; i++) {
            temp.push(dao_node.children[i]);
        }
        for (let i = 0; i < temp.length; i++) {
            temp[i].parent = this.node;
        }
        this.updataHandCards();
    },
});